package com.base.kit;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class StreamUtil {

    public static String stream2String(InputStream is) {
        return stream2String(is, "utf-8");
    }

    public static String stream2String(InputStream is, String charsetName) {
        if (null == is)
            return "";
        try (InputStreamReader inputStream = new InputStreamReader(is, charsetName);
             BufferedReader bufferedReader = new BufferedReader(inputStream)) {
            StringBuilder buffer = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                buffer.append(line);
            }
            closeStream(bufferedReader);
            closeStream(inputStream);
            return buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        } finally {
            closeStream(is);
        }
    }

    /**
     * 关闭流
     *
     * @param stream 可关闭的流
     */
    public static void closeStream(Closeable stream) {
        try {
            if (null == stream)
                return;
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
